<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px"
			class="queryForms">
			<el-form-item label="文件类型" prop="fileTypeId">
				<el-select v-model="queryParams.fileTypeId" placeholder="请选择">
					<el-option v-for="item in fileTypeList" :key="item.dictValue" :label="item.dictLabel"
						:value="item.dictValue"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="文件名称" prop="fileName">
				<el-input v-model="queryParams.fileName" placeholder="请输入设备名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button v-if="$route.query.type == '2'" type="primary" icon="el-icon-plus" size="mini"
					@click="handleCreate1" v-hasPermi="['army:information:create']">生成</el-button>
				<el-button v-if="$route.query.type == '1'" type="primary" icon="el-icon-plus" size="mini"
					@click="handleCreate" v-hasPermi="['army:information:create']">生成</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button v-if="$route.query.type == '2'" icon="el-icon-download" size="mini"
					@click="handleDownloadMore" v-hasPermi="['army:information:downloadAll']">下载</el-button>
				<el-button v-if="$route.query.type == '1'" icon="el-icon-download" size="mini"
					@click="handleDownloadMore" v-hasPermi="['army:information:downloadAll']">下载</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button size="mini" type="info" @click="handleBacks">返回</el-button>
			</el-col>
			<right-toolbar @changeTableData="changeTableData" menuNames="information4" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table ref="multipleTable" :data="fileList" v-loading="loading" @selection-change="handleSelectionChange"
				row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<!-- <el-table-column label="序号" align="center" type="index" width="60" /> -->
				<el-table-column label="文件类型" prop="fileType" min-width="180" :show-overflow-tooltip="true"
					v-if="columns[0].visible">
					<template slot-scope="scope">
						<span :class="scope.row.children.length > 0 ? '' : 'first-col-left'">{{ scope.row.fileType
							}}</span>
					</template>
				</el-table-column>
				<el-table-column label="文件名称" prop="fileName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[1].visible" />
				<el-table-column label="上传时间" align="center" prop="createTime" min-width="160"
					:show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="上传人员" align="center" prop="createBy" min-width="130"
					:show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="备注" align="center" prop="remark" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px"
					fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.parentId == 0">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleUpload(scope.row)"
								v-hasPermi="['army:information:upload']">上传</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-view" @click="handleScan(scope.row)"
								v-hasPermi="['army:information:scan']">预览</el-button>
							<el-button size="mini" type="text" icon="el-icon-download"
								@click="handleDownload(scope.row)"
								v-hasPermi="['army:information:download']">下载</el-button>
							<el-button v-if="$route.query.type == '1'" size="mini" type="text" icon="el-icon-delete"
								@click="handleDelete(scope.row)" v-hasPermi="['army:information:delete']">删除</el-button>
							<el-button v-if="$route.query.type == '2'" size="mini" type="text" icon="el-icon-delete"
								@click="handleDelete1(scope.row)"
								v-hasPermi="['army:information:delete']">删除</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
		<el-dialog title="上传文件" :visible.sync="uploadOpen" width="900px" append-to-body v-dialogDrag>
			<el-form :model="uploadForm" label-width="140px" class="add-form1">
				<el-form-item label="上传文件">
					<FileUpload @input="getFiles" :value="uploadList"></FileUpload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormUpload">确 定</el-button>
				<el-button @click="cancelUpload">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="下载文件" :visible.sync="downloadMoreOpen" width="900px" append-to-body v-dialogDrag>
			<el-form label-width="140px" class="add-form1">
				<el-form-item label="选择文件">
					<el-tree :data="downloadMoreOptions" show-checkbox default-expand-all node-key="value" ref="tree"
						highlight-current> </el-tree>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitDownload" :loading="downloading">确 定</el-button>
				<el-button @click="cancelDownload">取 消</el-button>
			</div>
		</el-dialog>
		<el-dialog title="预览" :visible.sync="openPreview" width="1000px" append-to-body v-dialogDrag>
			<previewExcel :previewUrl="previewUrl" :previewType="previewType"></previewExcel>
		</el-dialog>
	</div>
</template>

<script>
import previewExcel from "@/views/components/previewTemplete/excels.vue"
import { delFile1, uploadFile1, downloadfiles1, createFile1, armyfileList1, armyfileList, createFile, uploadFile, delFile, downloadfiles, getFileTypes } from "@/api/army/information"
import FileUpload from "@/components/FileUpload"
import { mapGetters } from "vuex"
export default {
	name: "Information",
	components: { FileUpload, previewExcel },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			status: 1,
			openPreview: false,
			previewType: "",
			previewUrl: "",
			eleTabTop: 0, //表格容器距浏览器顶部距离
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			deviceList: [],
			showSearch: true,
			queryParams: {},
			deviceTypeList: [],
			// 总条数
			total: 0,
			fileList: [],
			fileTypeList: [],
			// 上传
			uploadOpen: false,
			uploadList: [],
			uploadForm: {},
			// 多文件下载
			downloadMoreOpen: false,
			downloadMoreVal: [],
			downloadMoreOptions: [],
			downloading: false,
			// 列信息
			columns: [
				{ key: 0, label: `文件类型`, visible: true },
				{ key: 1, label: `文件名称`, visible: true },
				{ key: 2, label: `上传时间`, visible: true },
				{ key: 3, label: `上传人员`, visible: true },
				{ key: 4, label: `备注`, visible: true }
			]
		}
	},
	created() {
		this.loading = false
		// if (this.$route.query.type == 1) {
		// 	this.getList()
		// } else {
		// 	this.getList1()
		// }
		// this.getFileTypes()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		if (this.$route.query.type == 1) {
			this.getList()
		} else {
			this.getList1()
		} this.getFileTypes()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.multipleTable.doLayout()
			})
		},

		handleScan(row) {
			this.previewUrl = row.path
			this.previewType = row.path.substr(row.path.lastIndexOf(".") + 1)
			this.openPreview = true
		},
		getList1() {
			this.loading = true
			this.queryParams.id = this.$route.query.repairProductId
			armyfileList1(this.queryParams).then(response => {
				this.fileList = response.listfile
				this.loading = false
			})
		},
		handleBacks() {
			// 关闭当前tab页签，打开新页签
			const obj = { path: "/army/information" }
			this.$tab.closePage(obj).then(() => {
				this.$router.go(-1)
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		async getFileTypes() {
			let params = { typeId: 19 }
			let ret = await getFileTypes(params)
			this.fileTypeList = ret.data
		},
		handleReplace(row) {
			this.uploadOpen = true
			this.uploadList = []
		},
		// 上传
		handleUpload(row) {
			this.uploadOpen = true
			if (this.$route.query.type == 1) {
				this.uploadForm.armyExamineId = row.id
			}
			if (this.$route.query.type == 2) {
				this.uploadForm.primaryId = row.id
			}
			this.uploadList = []
		},
		submitFormUpload() {
			if (this.uploadList.length == 0) {
				this.$modal.msgError("请先上传文件")
				return false
			}
			this.uploadForm.fileList = this.uploadList
			if (this.$route.query.type == 1) {
				uploadFile(this.uploadForm).then(response => {
					this.$modal.msgSuccess("操作成功")
					this.uploadOpen = false
					this.getList()
				})
			}
			if (this.$route.query.type == 2) {
				uploadFile1(this.uploadForm).then(response => {
					this.$modal.msgSuccess("操作成功")
					this.uploadOpen = false
					this.getList1()
				})
			}
		},
		cancelUpload() {
			this.uploadOpen = false
		},
		// 上传
		getFiles(files) {
			this.uploadList = files
		},
		// 生成军检资料
		async handleCreate1() {
			const loading = this.$loading({
				lock: true,
				text: "Loading",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)"
			})
			let id = this.$route.query.repairProductId
			await createFile1(id)
			loading.close()
			this.$modal.msgSuccess("操作成功")
			this.getList1()
		},
		// 生成军检资料
		async handleCreate() {
			const loading = this.$loading({
				lock: true,
				text: "Loading",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)"
			})
			let id = this.$route.query.id
			await createFile(id)
			loading.close()
			this.$modal.msgSuccess("操作成功")
			this.getList()
		},

		/** 搜索按钮操作 */
		handleQuery() {
			// this.queryParams.pageNum = 1;
			if (this.$route.query.type == 1) {
				this.getList()
			} else {
				this.getList1()
			}
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		getList() {
			this.loading = true
			this.queryParams.id = this.$route.query.id
			armyfileList(this.queryParams).then(response => {
				this.fileList = response.listfile
				this.loading = false
			})
		},

		// 下载
		handleDownload(row) {
			// window.open(row.path);
			// 用fetch发送请求 对请求回来的二进制文件流进行处理
			fetch(row.path).then(res => {
				res.blob().then(blob => {
					const blobUrl = window.URL.createObjectURL(blob)
					// 这里的文件名根据实际情况从响应头或者url里获取
					const filename = row.fileName
					const a = document.createElement("a")
					a.href = blobUrl
					a.download = filename
					a.click()
					window.URL.revokeObjectURL(blobUrl)
				})
			})
		},

		// 多文件下载
		handleDownloadMore() {
			this.downloadMoreOpen = true
			let list = []
			this.fileList.forEach(item => {
				if (item.children && item.children.length > 0) {
					let curlist = []
					item.children.forEach(item1 => {
						let child = {
							value: item1.id,
							label: item1.fileName
						}
						curlist.push(child)
					})
					let cur = {
						value: item.id,
						label: item.fileType,
						children: curlist
					}
					list.push(cur)
				}
			})
			let option = [
				{
					value: 0,
					label: "全部",
					children: list
				}
			]
			this.downloadMoreOptions = option
		},
		submitDownload() {
			let values = this.$refs.tree.getCheckedKeys(true)
			if (values.length == 0) {
				this.$modal.msgError("请先选择文件")
				return false
			}
			this.downloading = true
			console.log(this.$route.query.type)
			if (this.$route.query.type == "1") {
				downloadfiles(values).then(response => {
					this.downloading = false
					if (response.url) {
						let fileName = "军检资料" + new Date().getTime()
						this.handleDownload({ path: response.url, fileName: fileName })
					}
					this.$modal.msgSuccess("操作成功")
					this.downloadMoreOpen = false
				})
			} else {
				downloadfiles1(values).then(response => {
					this.downloading = false
					if (response.url) {
						let fileName = "军检资料" + new Date().getTime()
						this.handleDownload({ path: response.url, fileName: fileName })
					}
					this.$modal.msgSuccess("操作成功")
					this.downloadMoreOpen = false
				})
			}
		},
		cancelDownload() {
			this.downloadMoreOpen = false
		},
		/** 删除按钮操作 */
		handleDelete1(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return delFile1(ids)
				})
				.then(() => {
					this.getList1()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return delFile(ids)
				})
				.then(() => {
					this.getList()
					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		}
	}
}
</script>
<style lang="scss" scoped>
.first-col-left {
	padding-left: 22px;
}
</style>
